package com.jshongli.myapplication.login;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jshongli.myapplication.MainActivity;
import com.jshongli.myapplication.R;
import com.jshongli.myapplication.base.BaseActivity;
import com.jshongli.myapplication.common.callback.MyCallback;
import com.jshongli.myapplication.common.callback.ObjectCallback;
import com.jshongli.myapplication.common.callback.ResponseCallback;
import com.jshongli.myapplication.common.utils.StringUtils;
import com.jshongli.myapplication.common.utils.ToastUtils;
import com.jshongli.myapplication.common.utils.UIUtils;
import com.jshongli.myapplication.common.utils.URLUtils;
import com.jshongli.myapplication.common.utils.UtilPreferences;
import com.jshongli.myapplication.common.view.ClearEditText;
import com.jshongli.myapplication.model.base.AppBean;
import com.jshongli.myapplication.model.base.StringBean;
import com.jshongli.myapplication.model.user.UserInfo;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends BaseActivity{

    @BindView(R.id.et_user)
    ClearEditText et_user;
    @BindView(R.id.et_pwd)
    ClearEditText et_pwd;

    @BindView(R.id.tv_login)
    TextView tv_login;

    @BindView(R.id.tv_version)
    TextView tv_version;

    @BindView(R.id.web)
    WebView mWebView;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        super.initView();

        mToolbar.setVisibility(View.GONE);

        if(UtilPreferences.hasString(mContext,"username"))
        {
            et_user.setText(UtilPreferences.getString(mContext,"username"));
        }
        if(UtilPreferences.hasString(mContext,"pwd"))
        {
            et_pwd.setText(UtilPreferences.getString(mContext,"pwd"));
        }

        getVersion();
        initWeb();
    }

    //region 创建webview
    private void initWeb() {
        mWebView = new WebView(this);
        mWebView.getSettings().setDefaultTextEncodingName("utf-8");
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new JsToJava(), "stub");  //JsToJava是内部类，代码在后面。stub是接口名字。
        mWebView.loadUrl("file:///android_asset/new_file.html"); //js文件路径
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
//                Log.e("webUrl",url);
//                String urlinit = "javascript:footballHelper.Es.jclq.setContent()";
//                mWebView.loadUrl(urlinit);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                Log.e("shouldOverri", url);
                return false;
            }
        });
    }

    private class JsToJava{
        @JavascriptInterface
        public void jsCallbackMethod(String result) {
//            Log.e("444", "result==" + result);
            new_login(result);
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    public void testJS(String json) {
        mWebView.loadUrl("javascript:getValue('"+json+"')");
    }


    //region 版本号
    private void getVersion() {
        PackageInfo packageInfo = null;
        try {
            packageInfo = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = packageInfo.versionName;
        tv_version.setText("版本号：V" + version);
    }
    //endregion

    @OnClick({R.id.tv_login})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_login:
                String username = et_user.getText().toString().trim();
                String password = et_pwd.getText().toString();

                if (StringUtils.editTextIsNull(et_user)) {
                    ToastUtils.show(mContext, "请先输入账号");
                    return;
                }
                if (StringUtils.editTextIsNull(et_pwd)) {
                    ToastUtils.show(mContext, "请先输入账号");
                    return;
                }

                UIUtils.showLoadingProgressDialog(LoginActivity.this, getString(R.string.waiting));

                login(username, password);
                break;

        }

    }

    private void login(String uName, String pwd) {
        testJS(pwd);
    }

    private void new_login(String jsonReqParams) {
        String url = URLUtils.URLNoToken("manageAPI/auth/login");

        Map<String, String> map = new HashMap<String, String>();
        map.put("username", et_user.getText().toString().trim());
        map.put("password", jsonReqParams);
        map.put("device", "App");

        Gson gson = new Gson();
        final String s = gson.toJson(map);

        OkHttpUtils
                .postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(s)
                .build()
                .execute(new MyCallback<StringBean>(mContext) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        super.onError(call, e, id);
                        UIUtils.cancelProgressDialog();
                    }


                    @Override
                    public void onSuccess(StringBean response) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                UIUtils.cancelProgressDialog();
                                if (response.success) {

                                    UtilPreferences.putString(mContext, "token", response.data);

                                    OkHttpUtils.get().url(URLUtils.URLNoToken("manageAPI/sysUser/getLoginUser")).addHeader("Authorization",response.data).tag(this)
                                            .build().execute(new MyCallback<UserInfo>(mContext) {


                                        @Override
                                        public void onSuccess(UserInfo response) {
                                           if(response.success)
                                           {
                                               UtilPreferences.putString(mContext, "userid", response.data.id);
                                               UtilPreferences.putString(mContext, "realname", response.data.realName);
                                               UtilPreferences.putString(mContext, "cable", response.data.cable);
                                               UtilPreferences.putString(mContext, "username", response.data.username);
                                               UtilPreferences.putString(mContext, "phone", response.data.phone);
                                               UtilPreferences.putString(mContext, "pwd", et_pwd.getText().toString());
                                               UtilPreferences.putString(mContext, "roleIds", response.data.roleIds);
                                               openActivity(MainActivity.class, true);
                                           }else {
                                               ToastUtils.show(mContext, "数据解析出错");
                                           }
                                        }
                                    });


                                } else if (!response.success) {
                                    ToastUtils.show(mContext, response.msg);
                                } else {
                                    ToastUtils.show(mContext, "数据解析出错");
                                }
                            }
                        }, 500);
                    }

                    @Override
                    public void onFail(StringBean response) {
                        super.onFail(response);
                        ToastUtils.show(mContext, response.msg);
                        UIUtils.cancelProgressDialog();
                    }

                });
    }
}